﻿using AutoMapper;
using Manager.Database;
using Manager.Model;
using Microsoft.EntityFrameworkCore;

namespace Manager.Service
{
    public class UserService
    {
        private readonly PCCSContext _context;
        private readonly IMapper _mapper;

        public UserService(PCCSContext context, IMapper mapper)
        {
            this._context = context;
            this._mapper = mapper;
        }

        public async Task<List<User>> GetUsersPaged(
            int pageNumber,
            int pageSize,
            string username,
            string sex,
            string state
        )
        {
            return await _context
                .users.Where(u =>
                    (string.IsNullOrEmpty(sex) ? true : u.sex == int.Parse(sex))
                    && (string.IsNullOrEmpty(username) ? true : u.username.Contains(username))
                    && (string.IsNullOrEmpty(state) ? true : u.state == int.Parse(state))
                )
                .Skip((pageNumber - 1) * pageSize)
                .Take(pageSize)
                .ToListAsync();
        }

        public async Task<int> GetTotalUsersCountAsync()
        {
            return await _context.users.CountAsync();
        }

        public User GetUserById(int id)
        {
            var user = _context.users.FirstOrDefault(u => u.id == id);
            var label = _context.labels.FirstOrDefault(l => l.id == user.labelId);
            if (user != null)
            {
                user.label = label;
            }
            return user;
        }

        public User UpdateUser(User user)
        {
            var dbUser = _context.users.FirstOrDefault(u => u.id == user.id);
            _mapper.Map(user, dbUser);
            _context.SaveChanges();
            return user;
        }

        public void DeleteUserById(int id)
        {
            var user = _context.users.Find(id);
            if (user != null)
            {
                _context.users.Remove(user);
                _context.SaveChanges();
            }
        }
    }
}
